<?php
require FORAGE_APP_PATH . '/behaviours/faceting/Facet.php';

/**
 * A ResponseBehaviour implementation for faceting.
 * This class provides the methods required to add faceting
 * to a response object. It adds methods such as adding facets,
 * their values and their counts and querying them.
 *
 * @author Rob Young <rob@roryoung.co.uk>
 * @package forage.behaviours.faceting
 */
class ForageFacetingResponseBehaviour extends ForageResponseBehaviour
{
  /**
   * The facets in this response
   *
   * @var array of ForageFacet objects
   */
  private $facets = array();

  public function __get($name)
  {
    switch ($name) {
    case 'facets':
      return $this->$name;
    case 'filter_facets':
      $facets = array();
      foreach ($this->facets as $facet) {
        if ($facet->isFilter()) {
          $facets[] = $facet;
        }
      }
      return $facets;
    case 'non_filter_facets':
      $facets = array();
      foreach ($this->facets as $facet) {
        if (!$facet->isFilter()) {
          $facets[] = $facet;
        }
      }
      return $facets;
    }
  }

  /**
   * Add a field, value combination with a count to this
   * result. Also sets whether this value is currently being 
   * filtered on.
   * If a facet with the provided field name already exists
   * add the value to it, otherwise create a new one and add.
   *
   * @param string $field
   * @param string $value
   * @param int $count
   * @param bool $filter
   */
  public function add($field, $value, $count, $filter=false)
  {
    if (!isset($this->facets[$field])) {
      $this->facets[$field] = new ForageFacet($field);
    }
    $this->facets[$field]->addValue($value, $count, $filter);
  }

  /**
   * Get a particular facet by it's name
   *
   * @return ForageFacet
   */
  public function getFacet($field) {
    foreach ($this->facets as $facet) {
      if ($facet->field == $field) {
        return $facet;
      }
    }
  }
}
